<template>
  <h1>个人中心</h1>
  <div v-for="(weibo,index) in arr" style="width: 500px;margin: 0 auto; height: 40px;">
    <!--    都是自己发的,所以不用体现作者的昵称 -->
    <h3 style="float: left; margin: 0;">{{ weibo.content }}</h3>
    <el-button type="danger" style="float: right;line-height: 32px" @click="del(weibo.id,index)">删除</el-button>
  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router";

const arr = ref([]);
onMounted(() => {
  // 获取当前登录的Id
  let user = localStorage.user ? JSON.parse(localStorage.user) : null;
  axios.get('http://localhost:8080/v1/weibos/selectByid?userId=' + user.id)
      .then((response) => {
        // 如果是响应式变量,必须要.value
        arr.value = response.data.data;
        if (arr.value.length == 0) {
          ElMessage.warning('快来发布你的第一条微博把');
          router.push('/post');
        }
      })
})

// 添加删除微博的方法
const del = (id, index) => {
  if (confirm('您是否要删除此条微博?')) {
    axios.post('http://localhost:8080/v1/weibos/' + id + '/delete').then((response) => {
          if (response.data.code == 2002) {
            ElMessage.success('删除成功');
            arr.value.splice(index, 1);
          }
          // 如果没有微博
          if (arr.value.length == 0) {
            ElMessage.warning('快来发布博吧!');
            //   跳转至发布页
            router.push('post')
          }
        })
  }
}
</script>

<style scoped>

</style>